package com.zeus.base.smscenter.shiro;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ShanFei on 2017-03-08.
 * Shiro权限异常处理
 */
@Component
public class ShiroHandleExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception exception) {
        boolean isAjax = com.zeus.base.smscenter.shiro.ShiroAjaxUtil.isAjax(httpServletRequest);
        if(exception instanceof AuthorizationException) {
            if(isAjax){
                httpServletResponse.setStatus(Integer.parseInt(com.zeus.base.smscenter.shiro.ShiroError.AuthorizationException)); //无权限异常
                Map<String,String> resultMap = new HashMap<String, String>();
                resultMap.put("success","false");
                resultMap.put("code", com.zeus.base.smscenter.shiro.ShiroError.AuthorizationException);
                resultMap.put("message","无权限");
                com.zeus.base.smscenter.shiro.ShiroAjaxUtil.out(httpServletResponse,resultMap);
                return new ModelAndView();
            }
            return new ModelAndView("redirect:/error.jsp");
        }else{
            exception.printStackTrace();
        }
        return null;
    }
}
